package sync

import (
	"promsync/nacos"
	"promsync/progress"
	"promsync/progress/log"
)

type Fetcher struct {
	Group  string
	DataId string
}

func (fetch *Fetcher) Listener(event chan string) {
	pidManager := &progress.PidManager{}
	defer func() {
		if err := recover(); err != nil {
			log.Log.Errorf("异常退出:%s", err)
			pidManager.RemovePid()
		}
	}()

	initConfig(fetch, event)

}

func initConfig(fetch *Fetcher, event chan string) {
	content, err := nacos.GetConfig(fetch.Group, fetch.DataId)
	if err != nil {
		log.Log.Errorf("获取config失败:group:%s dataId:%s,  %s", fetch.Group, fetch.DataId, err)
		panic("nacos获取配置异常")
		return
	}
	event <- content
	listenerConfig(fetch, event, content)
}

func listenerConfig(fetch *Fetcher, event chan string, content string) {
	err := nacos.ListenerConfig(fetch.Group, fetch.DataId, content, event)
	if err != nil {
		log.Log.Errorf("监听config失败:group:%s dataId:%s,   %s", fetch.Group, fetch.DataId, err)
	}
}

func (fetch *Fetcher) GetContent() string {
	content, err := nacos.GetConfig(fetch.Group, fetch.DataId)
	if err != nil {
		log.Log.Errorf("获取配置失败 ： group:%s, error:%s", fetch.Group, err)
		return ""
	}
	return content
}
